/*

* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Smart-Shop开源商城系统/ Java商城-首选电商平台系统 请务必保留此注释头信息
* |     开源地址: https://gitee.com/ningbo-qishan/gruul-mall
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     可正常分享和学习源码,未经授权 不可商用！
* |     商业版中台购买/开源版商业授权 联系技术客服
* |     官网:  https://www.73app.cn/
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Copyright (c) 2016-2999 宁波启山智软科技有限公司
* |     版权所有 ,侵权必究！
* ------------------------------------------------------------------------

*/
package com.medusa.gruul.live.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medusa.gruul.common.core.constant.CommonConstants;
import com.medusa.gruul.common.core.exception.ServiceException;
import com.medusa.gruul.common.core.util.CurUserUtil;
import com.medusa.gruul.common.core.util.Result;
import com.medusa.gruul.common.core.util.StringUtil;
import com.medusa.gruul.common.core.util.SystemCode;
import com.medusa.gruul.common.data.tenant.ShopContextHolder;
import com.medusa.gruul.common.data.tenant.TenantContextHolder;
import com.medusa.gruul.common.dto.CurShopInfoDto;
import com.medusa.gruul.live.api.entity.Live;
import com.medusa.gruul.live.api.model.dto.AssInfoDto;
import com.medusa.gruul.live.api.model.vo.RoomInfoVo;
import com.medusa.gruul.live.mapper.LiveMapper;
import com.medusa.gruul.live.model.param.api.ApiLiveParam;
import com.medusa.gruul.live.model.param.manager.LiveParam;
import com.medusa.gruul.live.model.vo.LiveVo;
import com.medusa.gruul.live.service.LiveService;
import com.medusa.gruul.live.utils.GlobalTools;
import com.medusa.gruul.live.utils.WechatLiveClient;
import com.medusa.gruul.platform.api.feign.RemoteMiniInfoService;
import com.medusa.gruul.platform.api.model.dto.MiniAuthInfoDto;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 直播 服务实现类
 * </p>
 *
 * @author zhaokw
 * @since 2020-4-6
 */
@Service
public class LiveServiceImpl extends ServiceImpl<LiveMapper, Live> implements LiveService {

    @Resource
    private LiveMapper liveMapper;


    @Resource
    private RemoteMiniInfoService remoteMiniInfoService;

    @Resource
    private WechatLiveClient wechatLiveClient;


    /**
     * 获取小程序端 直播列表信息
     *
     * @param apiLiveParam 分页信息
     * @return
     */
    @Override
    public IPage<LiveVo> getPageList(ApiLiveParam apiLiveParam) {
        //获取商铺id和租户id
        String shopId = ShopContextHolder.getShopId();
        String tenantId = TenantContextHolder.getTenantId();
        apiLiveParam.setShopId(shopId);
        apiLiveParam.setTenantId(tenantId);
        IPage<LiveVo> liveVoIPage =
                new Page<>(apiLiveParam.getCurrent(), apiLiveParam.getSize());
        //sql中查询数据
        List<LiveVo> liveVos =
                liveMapper.selectApiLiveList(apiLiveParam);
        liveVoIPage.setRecords(liveVos);
        return liveVoIPage;
    }





    /**
     * 获取直播分页信息
     *
     * @param liveParam
     * @return 直播分页对象
     */
    @Override
    public IPage<LiveVo> selectLiveList(LiveParam liveParam) {
        Page<LiveVo> objectPage = new Page<>(liveParam.getCurrent(), liveParam.getSize());
        List<LiveVo> liveVos = this.baseMapper.selectLiveList(objectPage, liveParam);
        liveVos = liveVos.stream().sorted(Comparator.comparing(LiveVo::getSort)).collect(Collectors.toList());
        return objectPage.setRecords(liveVos);
    }

    /**
     *  从微信获取直播列表
     * @param liveParam	
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.medusa.gruul.live.model.vo.LiveVo>
     * @author alan
     * @date 2021/3/17 22:10
     */
    @Override
    public IPage<LiveVo> getWeChatLiveList(LiveParam liveParam) {
        //从微信后台调取直播列表
        String tenantId = TenantContextHolder.getTenantId();
        String shopId = ShopContextHolder.getShopId();
        //tenantId = "100002";
        Result<MiniAuthInfoDto> miniAuthInfoDtoResult = remoteMiniInfoService.getMiniAuthInfo(tenantId);
        String accessToken = miniAuthInfoDtoResult.getData().getAccessToken();
        List<RoomInfoVo> roomInfoVos = wechatLiveClient.getLiveInfo(accessToken);
        LiveParam liveParam1 = new LiveParam();
        liveParam1.setTenantId(tenantId)
                .setShopId(shopId);
        List<LiveVo> liveVoList = liveMapper.queryLive(liveParam1);
        for (LiveVo liveVo : liveVoList) {
            boolean flag = false;
            for (RoomInfoVo roomInfoVo : roomInfoVos) {
                if (liveVo.getRoomId().equals(String.valueOf(roomInfoVo.getRoomid()))) {
                    flag = true;
                }
            }
            if (!flag) {
                liveMapper.deleteNotExist(liveVo.getId());
            }
        }

        //将信息存表
        for (RoomInfoVo roomInfoVo : roomInfoVos) {
            LiveParam liveParamTemp = new LiveParam();
            liveParamTemp.setTenantId(tenantId)
                    .setShopId(shopId)
                    .setRoomId(String.valueOf(roomInfoVo.getRoomid()));
            LiveVo liveVo = liveMapper.selectByRoomId(liveParamTemp);

            if (liveVo != null) {
                Live live = new Live();
                live.setAnchor(roomInfoVo.getAnchor_name())
                        .setEndTime(new Date(Long.parseLong(roomInfoVo.getEnd_time() + "000")))
                        .setLiveName(roomInfoVo.getName())
                        .setRoomId(String.valueOf(roomInfoVo.getRoomid()))
                        .setStartTime(new Date(Long.parseLong(roomInfoVo.getStart_time() + "000")))
                        .setStatus(roomInfoVo.getLive_status())
                        .setCoverImg(roomInfoVo.getCover_img())
                        .setAnchorImg(roomInfoVo.getAnchor_img())
                        .setShareImg(roomInfoVo.getShare_img())
                        .setId(liveVo.getId())
                        .setUpdateTime(LocalDateTime.now());

                int update = liveMapper.updateById(live);
                if (update < 1) {
                    throw new ServiceException("微信后台同步更新数据库失败", SystemCode.DATA_UPDATE_FAILED.getCode());
                }
            } else {
                Live live = new Live();
                live.setAnchor(roomInfoVo.getAnchor_name())
                        .setEndTime(new Date(Long.parseLong(roomInfoVo.getEnd_time() + "000")))
                        .setLikeCount(0L)
                        .setLiveName(roomInfoVo.getName())
                        .setRoomId(String.valueOf(roomInfoVo.getRoomid()))
                        .setStartTime(new Date(Long.parseLong(roomInfoVo.getStart_time() + "000")))
                        .setStatus(roomInfoVo.getLive_status())
                        .setViewCount(0L)
                        .setCoverImg(roomInfoVo.getCover_img())
                        .setAnchorImg(roomInfoVo.getAnchor_img())
                        .setShareImg(roomInfoVo.getShare_img());

                int insert = liveMapper.insert(live);
                if (insert < 1) {
                    throw new ServiceException("微信后台同步插入数据库失败", SystemCode.DATA_ADD_FAILED.getCode());
                }
            }
        }
        Page<LiveVo> objectPage = new Page<>(liveParam.getCurrent(), liveParam.getSize());
        List<LiveVo> liveVos = this.baseMapper.selectLiveList(objectPage, liveParam);
        return objectPage.setRecords(liveVos);
    }

    /**
     *  生成分享小程序码
     * @param 	
     * @return void
     * @author alan
     * @date 2021/3/17 22:10
     */
    @Override
    public void shareCode() {
        //从微信后台调取小程序码
        String tenantId = TenantContextHolder.getTenantId();
        String shopId = ShopContextHolder.getShopId();
        //tenantId = "100002";
        Result<MiniAuthInfoDto> miniAuthInfoDtoResult = remoteMiniInfoService.getMiniAuthInfo(tenantId);
        String accessToken = miniAuthInfoDtoResult.getData().getAccessToken();
        wechatLiveClient.getWechatCode(accessToken);

    }


    /**
     * @param liveParam
     * @Description: 更新团长id
     * @Author: zhaokw
     * @Date: 2020/4/6 23:59
     * @return: void
     **/
    @Override
    public void updateLaunchArea(LiveParam liveParam) {
        String tenantId = TenantContextHolder.getTenantId();
        String shopId = ShopContextHolder.getShopId();
        liveParam.setTenantId(tenantId);
        liveParam.setShopId(shopId);
        liveMapper.updateLaunchArea(liveParam);
    }



    /**
     * 比较两个数组是否有重复的值(有相同移除第一个数组中的相同值(常用))
     * */
    public static Object[] removeRepeat(Object[] arr1, Object[] arr2) {
        List<Object> list = new ArrayList<Object>(arr1.length);
        for (Object o1 : arr1) {
            list.add(o1);
            for (Object o2 : arr2) {
                if (o1.equals(o2)){
                    list.remove(o1);
                }
            }
        }
        return list.toArray();
    }



    /**
     * @param liveParam
     * @Description: 更新观看量
     * @Author: zhaokw
     * @Date: 2020/4/9 23:59
     * @return: void
     **/
    @Override
    public void updateViewCount(LiveParam liveParam) {
        String tenantId = TenantContextHolder.getTenantId();
        String shopId = ShopContextHolder.getShopId();
        liveParam.setTenantId(tenantId);
        liveParam.setShopId(shopId);
        liveMapper.updateViewCount(liveParam);
    }

    /**
     * @param liveParam
     * @Description: 更新点赞量
     * @Author: zhaokw
     * @Date: 2020/4/9 23:59
     * @return: void
     **/
    @Override
    public void updateLikeCount(LiveParam liveParam) {
        String tenantId = TenantContextHolder.getTenantId();
        String shopId = ShopContextHolder.getShopId();
        liveParam.setTenantId(tenantId);
        liveParam.setShopId(shopId);
        liveMapper.updateLikeCount(liveParam);
    }


    /**
     * 更新拖拽
     *
     * @param params
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSort(LinkedList<LiveParam> params) {
        if (params.size() < 1) {
            return Boolean.TRUE;
        }

        Long maxSort = params.stream().max(Comparator.comparing(LiveParam::getSort)).get().getSort();
        int size = params.size();
        for (int i = 0; i < params.size(); i++) {
            LiveParam param = params.get(i);
            param.setSort(maxSort - i);

            if (StringUtil.isNotEmpty(param.getId().toString())) {
                continue;
            }

            Live live = param.coverLive();
            size = size - this.baseMapper.updateById(live);
        }

        if (size > 0) {
            throw new ServiceException(String.format("批量修改失败! 操作已取消. 提交数: %s, 失败数: %s", params.size(), size));
        }

        return Boolean.TRUE;
    }

    /**
     * 更新直播状态
     */
    public void UpdateWeChatLive(){
        List<Live> lives = liveMapper.selectLiveInfo();
        if (CollectionUtil.isEmpty(lives)){
            log.warn("暂无直播信息");
        }
        Result<MiniAuthInfoDto> miniAuthInfoDtoResult;
        List<LiveVo> liveVoList;
        Live live ;
        for (Live liveInfo : lives) {
            String tenantId = liveInfo.getTenantId();
            String shopId = liveInfo.getShopId();
            miniAuthInfoDtoResult = remoteMiniInfoService.getMiniAuthInfo(tenantId);
            String accessToken = miniAuthInfoDtoResult.getData().getAccessToken();
            List<RoomInfoVo> roomInfoVos = wechatLiveClient.getLiveInfo(accessToken);
            LiveParam liveParam1 = new LiveParam();
            liveParam1.setTenantId(tenantId)
                    .setShopId(shopId);
            liveVoList = liveMapper.queryLive(liveParam1);
            for (LiveVo liveVo : liveVoList) {
                boolean flag = false;
                for (RoomInfoVo roomInfoVo : roomInfoVos) {
                    if (liveVo.getRoomId().equals(String.valueOf(roomInfoVo.getRoomid()))) {
                        flag = true;
                    }
                }
                if (!flag) {
                    liveMapper.deleteNotExist(liveVo.getId());
                }
            }

            //将信息存表
            for (RoomInfoVo roomInfoVo : roomInfoVos) {
                LiveParam liveParamTemp = new LiveParam();
                liveParamTemp.setTenantId(tenantId)
                        .setShopId(shopId)
                        .setRoomId(String.valueOf(roomInfoVo.getRoomid()));
                LiveVo liveVo = liveMapper.selectByRoomId(liveParamTemp);

                if (liveVo != null) {
                    live = new Live();
                    live.setAnchor(roomInfoVo.getAnchor_name())
                            .setEndTime(new Date(Long.parseLong(roomInfoVo.getEnd_time() + "000")))
                            .setLiveName(roomInfoVo.getName())
                            .setRoomId(String.valueOf(roomInfoVo.getRoomid()))
                            .setStartTime(new Date(Long.parseLong(roomInfoVo.getStart_time() + "000")))
                            .setStatus(roomInfoVo.getLive_status())
                            .setCoverImg(roomInfoVo.getCover_img())
                            .setAnchorImg(roomInfoVo.getAnchor_img())
                            .setShareImg(roomInfoVo.getShare_img())
                            .setId(liveVo.getId())
                            .setUpdateTime(LocalDateTime.now());

                    int update = liveMapper.updateById(live);
                    if (update < 1) {
                        throw new ServiceException("微信后台同步更新数据库失败", SystemCode.DATA_UPDATE_FAILED.getCode());
                    }
                } else {
                    live = new Live();
                    live.setAnchor(roomInfoVo.getAnchor_name())
                            .setEndTime(new Date(Long.parseLong(roomInfoVo.getEnd_time() + "000")))
                            .setLikeCount(0L)
                            .setLiveName(roomInfoVo.getName())
                            .setRoomId(String.valueOf(roomInfoVo.getRoomid()))
                            .setStartTime(new Date(Long.parseLong(roomInfoVo.getStart_time() + "000")))
                            .setStatus(roomInfoVo.getLive_status())
                            .setViewCount(0L)
                            .setCoverImg(roomInfoVo.getCover_img())
                            .setAnchorImg(roomInfoVo.getAnchor_img())
                            .setShareImg(roomInfoVo.getShare_img());

                    int insert = liveMapper.insert(live);
                    if (insert < 1) {
                        throw new ServiceException("微信后台同步插入数据库失败", SystemCode.DATA_ADD_FAILED.getCode());
                    }
                }
            }
        }
    }


}
